<template>
  <div class="app-container">
    <div class="topSearch">
      <el-row>
        <el-button type="primary" @click="orderPull()">
          Sync Order
        </el-button>
      </el-row>
    </div>
    <el-table
      v-loading="initLoading"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="Store Name">
        <template slot-scope="scope">
          {{ scope.row.name }}
          <el-progress
            v-if="
              idArr.indexOf(scope.row.id) > -1 &&
                idError.indexOf(scope.row.id) === -1 &&
                percentageObj[scope.row.id] !== 100
            "
            :percentage="percentageObj[scope.row.id]"
          />
          <div v-if="idError.indexOf(scope.row.id) > -1" class="syncErr">
            <el-alert
              :title="percentageError[scope.row.id]"
              show-icon
              type="error"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="Store Type">
        <template slot-scope="scope">
          {{ storeMap[scope.row.type] }}
        </template>
      </el-table-column>
      <el-table-column prop="orderLastSyncTime" label="Last Sync Time" />
      <el-table-column label="Action">
        <template slot-scope="scope">
          <el-button
            v-preventReClick
            type="text"
            @click="orderPull(scope.row.id)"
          >Sync</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { authorizedList, orderPull, orderPullResult } from '@/api/authorized';
export default {
  data() {
    return {
      initLoading: false,
      tableData: [],
      storeMap: {
        1: 'Shopify',
        2: 'WooCommerce'
      },
      multipleSelection: [],
      idArr: [],
      percentageObj: {},
      idError: [],
      percentageError: {},
      timerNum: null,
      timerResult: null
    };
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    clearInterval(this.timerNum);
    clearInterval(this.timerResult);
  },
  methods: {
    init() {
      this.initLoading = true;
      authorizedList({
        storeType: 'VIRTUAL'
      }).then((res) => {
        this.initLoading = false;
        const data = res.data.filter((item) => item.type !== 4);
        this.tableData = data;
      });
    },
    orderPull(id) {
      let ids = [];
      if (id !== undefined) {
        ids[ids.length] = id;
      } else {
        if (this.multipleSelection.length === 0) {
          return this.$message.warning('Please select at least one');
        }
        ids = this.multipleSelection.map((item) => item.id);
      }
      orderPull(ids).then((res) => {
        if (res.code === 200) {
          const idArr = [];
          const percentageObj = {};
          const taskIds = [];
          res.data.forEach((item) => {
            idArr.push(item.storeId);
            if (item.taskId < 0) {
              percentageObj[item.storeId] = 0;
            } else {
              percentageObj[item.storeId] = 0;
            }
            if (item.taskId > 0) {
              taskIds.push(item.taskId);
            }
          });
          this.percentageObj = percentageObj;
          this.idArr = idArr;
          this.timerNum = setInterval(() => {
            if (JSON.parse(JSON.stringify(this.percentageObj)) !== {}) {
              for (var key in this.percentageObj) {
                if (this.percentageObj[key] === 100) {
                  delete this.percentageObj[key];
                } else if (this.percentageObj[key] + 1 < 100) {
                  this.percentageObj[key] += 1;
                }
              }
            } else {
              clearInterval(this.timerNum);
            }
          }, 500);
          this.timerResult = setInterval(() => {
            orderPullResult(taskIds).then((res) => {
              if (res.code !== 200) {
                clearInterval(this.timerResult);
              } else {
                var status = true;
                const percentageError = {};
                const idError = [];
                res.data.forEach((item) => {
                  if (item.status === 2) {
                    taskIds.splice(taskIds.indexOf(item.taskId), 1);
                    this.$set(this.percentageObj, item.storeId, 100);
                    delete this.percentageObj[item.storeId];
                    this.idArr.forEach((t, i) => {
                      if (t === item.storeId) {
                        this.idArr.splice(i, 1);
                      }
                    });
                    this.tableData.forEach((it, index) => {
                      if (it.id === item.storeId) {
                        it.orderLastSyncTime = item.finishTime;
                        this.$set(this.tableData, index, it);
                      }
                    });
                  } else if (item.status === 1) {
                    status = false;
                  } else if (item.status === 3) {
                    taskIds.splice(taskIds.indexOf(item.taskId), 1);
                    delete this.percentageObj[item.storeId];
                    this.idArr.forEach((t, i) => {
                      if (t === item.storeId) {
                        this.idArr.splice(i, 1);
                      }
                    });
                    percentageError[item.storeId] = item.note;
                    idError.push(item.storeId);
                  }
                });
                this.percentageError = percentageError;
                this.idError = idError;
                if (status) {
                  clearInterval(this.timerResult);
                }
              }
            });
          }, 3000);
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 10px 0;
}
.syncErr {
  .el-alert {
    position: absolute;
    max-width: 600px;
    z-index: 20;
    top: 0px;
    left: 100px;
    padding: 4px 30px 4px 8px;
    ::v-deep.el-alert__closebtn {
      top: 10px;
    }
  }
}
</style>
